In C, an array of strings is a collection of multiple strings, where each string is an array of characters. Each string in the array is terminated by a null character ('\0'), which marks the end of the string. An array of strings can be visualized as a two-dimensional array, where each row represents a string.
To declare an array of strings in C, you need to declare a two-dimensional character array (a 2D array of characters), where each row represents a string. The size of the array should be specified based on the maximum length of the strings it will hold.
char array_name[num_of_strings][max_string_length + 1];
The +1 in the size accounts for the null character at the end of each string.
#include <stdio.h>
#include <string.h>
int main() {
// Declaration and initialization of an array of strings
char names[3][20] = {
"Alice",
"Bob",
"Charlie"
};
// Printing the array of strings
printf("Array of Strings:\n");
for (int i = 0; i < 3; i++) {
printf("%s\n", names[i]);
}
// Accessing individual characters in a string
printf("First character of the second string: %c\n", names[1][0]); // 'B'
// Modifying a string
strcpy(names[2], "David");
// Printing the modified array of strings
printf("Modified Array of Strings:\n");
for (int i = 0; i < 3; i++) {
printf("%s\n", names[i]);
}
return 0;
}
Array of Strings:
Alice
Bob
Charlie
First character of the second string: B
Modified Array of Strings:
Alice
Bob
David
What is an array of strings in C?
How do you declare an array of strings in C?
How do you initialize an array of strings in C?
How can you access individual characters in an array of strings in C?
What is the significance of the null character in C strings?